
//
//  WaitPayTestViewController.m
//  MIDI
//
//  Created by E.M.Game on 15/9/30.
//  Copyright (c) 2015年 QXSX. All rights reserved.
//

#import "WaitPayTestViewController.h"
#import "AppConfig.h"
#import "WaitPayTestCell.h"
#import "UIViewController+NavItem.h"
#import "APIAdress.h"
#import "MBProgressHUD+YC.h"
#import "QXNetWorkTool.h"
#import "TestDetailModel.h"
#import "PrepareGuideViewController.h"
#import "CertificatePayTipViewControl.h"
#import "SIAlertView.h"
#import "WaitForTestViewController.h"
#import "MyTestViewController.h"
#import "WXApi.h"
#import "UserDataSingleton.h"
#import "MusicTextBookOrderModel.h"
#import "AccountTool.h"
#import "AliPayTool.h"
#import "WXPrePayIdModel.h"
#import "WeChatPayTool.h"
#import "PaySignCostAndCerficationCostModel.h"
#import "CommFunc.h"

@interface WaitPayTestViewController ()<UITableViewDataSource , UITableViewDelegate,
                                        QXNetWorkToolDelegate, CertificatePayTipViewDeletage>

@property (weak, nonatomic) IBOutlet UITableView *myTableView;
@property (nonatomic , strong) TestDetailModel *model;
@property(strong , nonatomic) PaySignCostAndCerficationCostModel * orderData; //订单数据
@property(assign , nonatomic) int payType;
@property(strong , nonatomic) WaitPayTestCell *myCell;


@end

@implementation WaitPayTestViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    [self config];
    
    self.payType = -1;
    
    self.myTableView.showsVerticalScrollIndicator = NO;
    self.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}

- (void)config
{
    [MBProgressHUD showMessage:@"正在加载" toView:self.view];
    QXNetWorkTool *tool = [[QXNetWorkTool alloc]init];
    
    tool.QXNetWorkDelegate = self;
    
    [tool GetDataFromServerWithPostMethodandInterfaceName:ExamDetailInterface andParameter:@[@{@"exam_id":self.exam_id}] tag:1];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self configNavigationItem];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

-(void) configNavigationItem
{
    [self.navigationController.navigationBar setBarTintColor:MIDIColorOfNavigationBar];
    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    self.navigationItem.title = @"等待缴费";
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],UITextAttributeTextColor, [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1.0],UITextAttributeTextShadowColor,[UIFont fontWithName:@"Hiragino Sans GB" size:18.0],UITextAttributeFont,nil]];
    
    [self configNavigationBackAction:^{
        
        [self.navigationController popViewControllerAnimated:YES];
    }];
    
}

#pragma mark tableView datasource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.myCell) {
        return [self.myCell getHeight];
    }
    return 463;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.myCell = nil;
    NSString *identifier = @"WaitPayTestCellTableViewCell";
    self.myCell = [self.myTableView dequeueReusableCellWithIdentifier:identifier];
    if(self.myCell == nil)
    {
        self.myCell = [WaitPayTestCell loadFromeXib];
    }
    
    if (self.myCell && self.model)
    {
        self.myCell.contentView.hidden = NO;
        [self configCell:indexPath.row cell:self.myCell];
    }
    
    return self.myCell;
}

#pragma mark - Table View Delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

- (void)configCell :(NSInteger)row cell:(WaitPayTestCell *) mycell
{
    if ([self.model.major_name isEqualToString:@"音乐基础"])
    {
        mycell.testItemImg.image = [UIImage imageNamed:@"Img_myTestStatus_musicBase"];
    }
    else if ([self.model.major_name isEqualToString:@"爵士鼓"])
    {
        mycell.testItemImg.image = [UIImage imageNamed:@"img_myTestStatus_jueshigu"];
    }
    else if ([self.model.major_name isEqualToString:@"电吉他"])
    {
        mycell.testItemImg.image = [UIImage imageNamed:@"img_myTestStatus_dianjita"];
    }
    else if ([self.model.major_name isEqualToString:@"电贝司"])
    {
        mycell.testItemImg.image = [UIImage imageNamed:@"img_myTestStatus_dianbeisi"];
    }
    
    mycell.testNameLb.text = self.model.major_name;
    
    if ([mycell.testNameLb.text isEqualToString:@"音乐基础"])
    {
        mycell.testNameLb.text = @"音乐理论";
    }
    
    NSString *str = @"￥";
    if (self.model.cost)
    {
        str = [str stringByAppendingString:self.model.cost];
        [mycell.priceBtn setTitle:str forState:UIControlStateNormal];
    }
    
    str = @"地点:  ";
    if (self.model.exam_site_name)
    {
        mycell.addrLb.text = [str stringByAppendingString:self.model.exam_site_name];
    }
    mycell.timeLb.text = self.model.exam_time;
    
    if (self.model.grade_num)
    {
        if ([mycell.testNameLb.text isEqualToString:@"音乐理论"])
        {
            mycell.levelLb.text = [CommFunc getMusicBaseLevel:self.model.grade_num];
        }
        else
        {
            mycell.levelLb.text = [self.model.grade_num stringByAppendingString:@"级"];
        }
    }

    mycell.phoneNumberLb.text = self.model.tel;
    mycell.detailLb.text = self.model.detail;
    
    [mycell.button1 addTarget:self action:@selector(prepare:) forControlEvents:UIControlEventTouchUpInside];
    
    [mycell.button2 addTarget:self action:@selector(payTip:) forControlEvents:UIControlEventTouchUpInside];
}

-(void)ConfirmatePaySignCostOverdue
{
    [MBProgressHUD showMessage:@"正在加载" toView:self.view];
    QXNetWorkTool *tool = [[QXNetWorkTool alloc]init];
    
    tool.QXNetWorkDelegate = self;
    
    [tool GetDataFromServerWithPostMethodandInterfaceName:ConfirmatePaySignCostOverdueInterface andParameter:@[@{@"exam_id":self.exam_id}] tag:4];
}

-(void)prepare:(UIButton *)sender
{
    //备考
    [self.navigationController pushViewController:
     [PrepareGuideViewController create] animated:YES];
}

-(void)payTip:(UIButton *)sender
{
    [self ConfirmatePaySignCostOverdue];
    return;
}

-(void)payChoiceBox
{
    if (self.model == nil)
        return;
    
    CertificatePayTipViewControl *obj = [CertificatePayTipViewControl create];
    obj.view.backgroundColor = [UIColor clearColor];
    obj.bgImage.alpha = 1;
    obj.tipLabel.hidden = YES;
    
    UIView *subView = [obj.view viewWithTag:999];
    subView.backgroundColor = [UIColor clearColor];
    
    obj.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    obj.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    obj.definesPresentationContext = YES;
    obj.deletage = self;
    
    [obj setTitleData:self.model.cost];
    [self presentViewController:obj animated:YES completion:nil];
}

//支付运费
-(void)pay:(int)type
{
    if (type == 1) //微信
    {
        UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"确认支付" message:nil
                                                            delegate:self cancelButtonTitle:@"取消"otherButtonTitles:@"确定",nil];
        
        alertView.tag = 111;
        
        [alertView show];
    }
    else if (type == 2) //支付宝
    {
        UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"确认支付" message:nil
                                                            delegate:self cancelButtonTitle:@"取消"otherButtonTitles:@"确定",nil];
        
        alertView.tag = 222;
        
        [alertView show];
    }
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 111)
    {
        //微信支付
        if (buttonIndex == 1)
        {
            self.payType = 0;
            [self WXPay];
            return;
        }
    }
    else if (alertView.tag == 222)
    {
        //支付宝支付
        if (buttonIndex == 1)
        {
            self.payType = 1;
            [self Alipay];
            return;
        }
    }
    else if (alertView.tag == 333)
    {
        //没有装微信
        return;
    }
}

-(void) WXPay
{
    if(![WXApi isWXAppInstalled]) // 判断 用户是否安装微信
    {
        UIAlertView *alertView = [[UIAlertView alloc]
                                  initWithTitle:@"您未安装微信，请安装后付款。"
                                  message:nil
                                  delegate:self
                                  cancelButtonTitle:@"确定"
                                  otherButtonTitles:nil, nil];
        
        alertView.tag = 333;
        [alertView show];
        return;
    }
    
    [self createOrder];
}

-(void) Alipay
{
    [self createOrder];
}

-(void) createOrder
{
    //生成订单
    UserDataSingleton *userData = [UserDataSingleton shareInstance];
    if(![userData isLogin])
    {
        [userData pleaseLogin:self];
        return;
    }
    
    [MBProgressHUD showMessage:@"正在加载" toView:self.view];
    
    QXNetWorkTool *netTools = [[QXNetWorkTool alloc]init];
    netTools.QXNetWorkDelegate = self;
    
    [netTools GetDataFromServerWithPostMethodandInterfaceName:PaySignCostAndCerficationCostInterface andParameter:
     @[@{@"exam_id":self.model.id,
         @"type":@"1"}] tag:2];
}

-(void)GetSuccessResponse:(id)Response andTag:(int)tag
{
    [MBProgressHUD hideHUDForView:self.view];

    switch (tag)
    {
        case 1:
        {
            for (NSDictionary *dic in Response)
            {
                self.model = [TestDetailModel TestDetailWithDict:dic];
                
                break;
            }
            [self.myTableView reloadData];
            break;
        }
        case 2:
        {
            //生成订单
            for(NSDictionary * dic in Response)
            {
                PaySignCostAndCerficationCostModel * item = [PaySignCostAndCerficationCostModel PaySignCostAndCerficationCostWithDict:dic];
                
                self.orderData = item;
            
                [AccountTool saveOrderId:item.order_num];
                
                break;
            }
            
            if (self.payType == 0)
            {
                QXNetWorkTool *netTools = [[QXNetWorkTool alloc]init];
                netTools.QXNetWorkDelegate = self;
                
                //微信支付
                int wxPrice = [self.model.cost floatValue] * 100;
                NSString *strPrice = [[NSString alloc] initWithFormat:@"%d", wxPrice];
                
                //获得prepayid和noncestr
                [netTools GetDataFromServerWithPostMethodandInterfaceName:WXPayGetPrepayIdInterface andParameter:
                 @[@{
                       @"totalfee":strPrice,
                       @"body":@"考试报名费",
                       @"outtradeno":self.orderData.order_num
                       }] tag:3];
            }
            else if (self.payType == 1)
            {
                //支付宝支付
                
                [AccountTool saveExamId:self.model.id];
                [AccountTool savePayItem:VPaySignCost];
                
                [AliPayTool alipayWithOrdercode:@"" orderId:self.orderData.order_num Price:self.model.cost CityId:@"" Target:self];
            }
            
            self.payType = -1;
            
            break;
        }
        case 3:
        {
            for(NSDictionary * dic in Response)
            {
                WXPrePayIdModel * item = [WXPrePayIdModel WXPrePayIdModelWithDict:dic];
                
                NSString *prepayid = item.prepayid;
                NSString *noncestr = item.noncestr;
                
                int wxPrice = [self.model.cost floatValue] * 100;
                NSString *strPrice = [[NSString alloc] initWithFormat:@"%d", wxPrice];
                
                //微信支付
                
                [AccountTool saveExamId:self.model.id];
                [AccountTool savePayItem:VPaySignCost];
                
                [WeChatPayTool WeChatWithOrdercode:@""
                                          prepayid:prepayid
                                           orderId:self.orderData.order_num
                                            Price :strPrice
                                            CityId:@""
                                          noncestr:noncestr
                                            Target:self];
                break;
            }
        }
        case 4:
        {
            //缴纳报名费时间没有过期
            [self payChoiceBox];
            break;
        }
    }
}

- (void)GetFailResponse:(id)Response andTag:(int)tag
{    
    switch (tag)
    {
        case 6666:
        case 7777:
        case 8888:
            [MBProgressHUD hideHUD];
            //            [MBProgressHUD showSuccess:(NSString*)message];
            break;
        default:
        {
            [MBProgressHUD hideHUDForView:self.view];
            [MBProgressHUD showError:(NSString*)Response toView:self.view];
            break;
        }
    }
}

- (void)GetSuccessMessage:(id)message andTag:(int)tag
{
    switch (tag)
    {
        case 6666:
            break;
        case 7777:
        case 8888:
            //支付成功后，返回我的考试
            [MBProgressHUD hideHUD];
            [self.navigationController popViewControllerAnimated:YES];
            break;
    }
}

//-(void)payResultOtherProcess:(NSDictionary *)resultDic
//{
//    if ([resultDic[@"resultStatus"] isEqualToString:@"9000"] )
//    {
//        //支付成功后，调回我的考试
//        [self.navigationController popViewControllerAnimated:YES];
//        
////        //支付成功后，调回我的考试
////        for (UIViewController *controller in self.navigationController.viewControllers) {
////            if ([controller isKindOfClass:[MyTestViewController class]])
////            {
////                [self.navigationController popToViewController:controller animated:NO];
////            }
////        }
//    }
//}

@end





















